#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define KB_SIZE 1024
#define MB_SIZE (1024 * KB_SIZE)
#define GB_SIZE (1024 * MB_SIZE)
#define BUF_4K (4 * KB_SIZE)

int main()
{
    // 源文件
    char src_file[32] = "test.img";
    int src_fd = open(src_file, O_RDONLY);
    if (src_fd < 0)
    {
        perror("open");
        return -1;
    }

    // 目标文件
    char dst_file[32] = "test2.2.img";
    int dst_fd = open(dst_file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if (dst_fd < 0)
    {
        perror("open");
        return -1;
    }
    // 写文件缓存优化
    posix_fadvise(src_fd, 0, 4096, POSIX_FADV_DONTNEED);
    // posix_fadvise(src_fd, 0, 0, POSIX_FADV_NOREUSE);

    // char buf[4096];
    int len;
    int count = 0;
    int half_count = 512 * MB_SIZE / 4096 - 1;
    while (1)
    {
        uint8_t* buf = malloc(4096);
        if (buf == NULL){
            perror("malloc failed: ");
            break;
        }
        memset(buf, 0, 4096);

        len = read(src_fd, buf, 4096);
        if (len <= 0)
            break;
        write(dst_fd, buf, len);

        count ++;
        // printf("read %d bytes\n", len);

        if(count == half_count)
        {
            printf("输入任意按键继续\n");
            fgets((char *)buf, 4096, stdin);
        }

        free(buf);
    }
    close(src_fd);
    close(dst_fd);

    printf("read %d times\n", count);
}